package com.example.demo.jwt;

import com.example.demo.bean.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * 自定义用户详情服务
 * 实现 Spring Security 的 UserDetailsService 接口
 * @author Administrator
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final UserMapper userMapper;

    @Autowired
    public CustomUserDetailsService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        // 直接使用数据库中的角色，不添加前缀
        String role = user.getRole();
        if (role == null || role.isEmpty()) {
            role = "USER";  // 默认角色
        }

        return new org.springframework.security.core.userdetails.User(
            user.getUname(),
            user.getUpwd(),
            Collections.singletonList(new SimpleGrantedAuthority(role))
        );
    }
} 